/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-11-18 23:27:03
 * @LastEditors: lhl
 * @LastEditTime: 2024-11-18 23:27:14
 */
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface TabItem {
  key: string;
  label: string;
  closable: boolean;
}

interface TabsState {
  tabs: TabItem[];
  activeKey: string;
}

const initialState: TabsState = {
  tabs: [
    {
      key: '/dashboard',
      label: '首页',
      closable: false,
    },
  ],
  activeKey: '/dashboard',
};

const tabsSlice = createSlice({
  name: 'tabs',
  initialState,
  reducers: {
    addTab: (state, action: PayloadAction<TabItem>) => {
      if (!state.tabs.find((tab) => tab.key === action.payload.key)) {
        state.tabs.push(action.payload);
      }
      state.activeKey = action.payload.key;
    },
    removeTab: (state, action: PayloadAction<string>) => {
      const index = state.tabs.findIndex((tab) => tab.key === action.payload);
      if (index !== -1) {
        state.tabs.splice(index, 1);
        if (state.activeKey === action.payload) {
          state.activeKey = state.tabs[state.tabs.length - 1].key;
        }
      }
    },
    setActiveKey: (state, action: PayloadAction<string>) => {
      state.activeKey = action.payload;
    },
  },
});

export const { addTab, removeTab, setActiveKey } = tabsSlice.actions;
export default tabsSlice.reducer;
